package cn.itcast.work.intercepter;


import cn.itcast.work.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * 实现拦截器类 的拦截用户的页面
 */
public class PermissionIntercepter implements HandlerInterceptor{
//	首先执行 进行判断其他页面是否登录拦截
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println("执行了PermissionIntercepter----------preHandle");
		//从会话中得到 信息 如果没有则被拦截
		User user=(User) request.getSession().getAttribute("user");
		String phone =(String)request.getSession().getAttribute("phone");
		if(user==null){
			System.out.println("空字符");
			//存入信息
//			request.setAttribute("msg", "未经登录,不允许访问,请先登录!");
			System.out.println("拦截器执行了");
			//获取当前请求的路径
			String basePath = request.getScheme() + "://" + request.getServerName() + ":"  + request.getServerPort()+request.getContextPath();
			//如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求，需要特殊处理 否则直接重定向就可以了
			if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
//				request.getRequestDispatcher("/WEB-INF/jsp/Login.jsp").forward(request, response);
				//告诉ajax我是重定向
				request.setAttribute("msg", "未经登录,不允许访问,请先登录!");
				System.out.println("进入ajax判断");
				response.setHeader("REDIRECT", "REDIRECT");
				//告诉ajax我重定向的路径
				response.setHeader("CONTEXTPATH", "/blog/intoLogin");
				response.setStatus(HttpServletResponse.SC_FORBIDDEN);
			}else{
				System.out.println("不是");
				request.getRequestDispatcher("/WEB-INF/jsp/Login.jsp").forward(request, response);
//				response.sendRedirect(basePath + "/WEB-INF/jsp/Login.jsp");
			}
			return false;
		}
		return true;

	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception arg3)
			throws Exception {
		System.out.println("执行了PermissionIntercepter----------afterCompletion");
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
		System.out.println("执行了PermissionIntercepter----------postHandle");
	}
}


